<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="isLoading">
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click.native="addRule"
            >新增角色</el-button>
            <!-- 表格 -->
            <el-table :data="ruleList">
              <el-table-column label="序号" width="100" type="index" :index="indexMethod" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click.native="addAssign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click.native="editList(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click.native="removeList(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <!-- 公司信息 -->
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <div class="block" style="display:flex;justify-content:flex-end;">
        <el-pagination
          :current-page="page"
          :page-sizes="[10, 20, 30]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <el-dialog :title="ChangeTitle" :visible="showDialog" :close-on-click-modal="false" @close="closeDialog">
        <el-form ref="roleForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click.native="addRulesYes">确认</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        :close-on-click-modal="false"
        @close="closeAssignDialog"
        @open="openDialogFn"
      >
        <el-tree
          ref="tree"
          v-loading="treeLoading"
          :data="permissionList"
          :props="{label:'name'}"
          default-expand-all
          show-checkbox
          node-key="id"
          check-strictly
        />
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click.native="addSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getRuleListAPI, removeRulelistAPI, addRulelistAPI, editHuixianAPI, editRulelistAPI, getCompanyIDAPI, setPermissonAPI } from '@/api/settings'
import { mapGetters } from 'vuex'
import { getPermissionListAPI } from '@/api/permission'
import { getlist } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      page: 1, // 默认第一页
      pagesize: 10, // 每页10条
      ruleList: [], // table列表数据
      total: 0, // 接口所有的数据
      isLoading: false, // 加载效果
      showDialog: false, // 控制弹框的关闭隐藏
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '公司名称必填', trigger: 'blur' }]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      showAssignDialog: false,
      RuleId: '',
      permissionList: [],
      treeLoading: false
    }
  },
  // 通过计算属性控制标题
  computed: {
    ...mapGetters(['companyId']),
    ChangeTitle() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    // 在created里调用方法 获取角色列表数据
    this.getRuleList()
    // 调获取公司信息方法
    this.getCompanyID()
  },
  methods: {
    // 关闭弹框方法
    closeAssignDialog() {
      this.showAssignDialog = false
    },
    addAssign(id) {
      this.showAssignDialog = true
      this.RuleId = id
    },
    // 打开弹窗的方法
    async openDialogFn() {
      this.treeLoading = true
      await this.getPermissionList()
      await this.getPermission()
      this.treeLoading = false
    },
    // 封装获取权限点列表方法
    async getPermissionList() {
      const { data } = await getPermissionListAPI()
      this.permissionList = getlist(data, '0')
    },
    // 封装数据回显的方法
    async getPermission() {
      const { data: { permIds }} = await editHuixianAPI(this.RuleId)
      // console.log(permIds)
      this.$refs.tree.setCheckedKeys(permIds)
    },
    // 点击确定的方法
    async addSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys()
      // console.log(permIds)
      await setPermissonAPI({ id: this.RuleId, permIds })
      this.$message.success('给角色分配权限成功')
      this.closeAssignDialog()
    },

    // =========================以上是给角色分配权限方法=========================
    // 封装获取公司信息方法
    async getCompanyID() {
      const { data } = await getCompanyIDAPI(this.companyId)
      this.companyForm = data
    },
    // 封装获取角色列表方法
    async  getRuleList() {
      this.isLoading = true
      const { data } = await getRuleListAPI(this.page, this.pagesize)
      this.ruleList = data.rows
      this.total = data.total
      this.isLoading = false
      // console.log(data)
    },
    // 封装删除角色列表方法 1. 询问框 2. 掉接口 3. 提示 4. 重新获取数据
    removeRulelist(id) {
      this.$confirm('你确定要删除吗', '温馨提示').then(async() => {
        await removeRulelistAPI(id)
        this.$message.success('删除成功')
        if (this.ruleList.length === 1 && this.page > 1) {
          this.page--
        }
        this.getRuleList()
      }).catch(() => {
        // 取消删除什么都不做
      })
    },
    // 当我们点击删除按钮的方法
    removeList(id) {
      this.removeRulelist(id)
    },
    // 点击切换页码的方法
    handleCurrentChange(val) {
      // console.log(val + '当前')
      this.page = val
      this.getRuleList()
    },
    // 点击切换页容量触发的方法
    handleSizeChange(val) {
      // console.log(val)
      this.pagesize = val
      this.getRuleList()
    },
    // 修改页面的序号为正确的方法
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 封装点击添加的方法
    addRule() {
      this.showDialog = true
    },
    // 封装点击编辑的方法
    async editList(id) {
      this.showDialog = true
      const { data } = await editHuixianAPI(id)
      // console.log(data)
      this.form = data // 数据回显
    },
    // 封装关闭弹层方法
    closeDialog() {
      this.showDialog = false
      // 下边这个只能清空prop绑定的数据和规则
      this.$refs.roleForm.resetFields()
      this.form = { // 手动清空表单
        name: '',
        description: ''
      }
    },
    // 封装点击确认方法
    addRulesYes() {
      // 点击确认的时候做兜底验证
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return
        if (this.form.id) {
          await editRulelistAPI(this.form) // 调修改接口
          this.$message.success('修改角色成功')// 成功提示
        } else {
          await addRulelistAPI(this.form)// 调添加接口
          // console.log(res)
          this.$message.success('添加角色成功')// 成功提示
        }
        this.closeDialog() // 关闭弹窗
        this.getRuleList() // 重新拉取数据
      })
    }

  }
}
</script>

<style>

</style>
